const app = getApp();
const { mockData, searchSongs } = require('../../utils/mock-data');

Page({
  data: {
    // 搜索相关
    searchKeyword: '',
    showSearchModal: false,
    searchResults: [],
    
    // 音乐数据
    hotSongs: [],
    playlists: [],
    currentSong: null,
    isPlaying: false,
    currentTime: 0,
    
    // 播放列表
    playList: [],
    currentIndex: 0,
    
    // 播放模式
    playMode: 'sequence',
    playModeIcon: 'icon-sequence',
    
    // 歌词显示
    showLyric: false,
    lyricData: []
  },

  onLoad() {
    this.initData();
    this.setupAudioListener();
  },

  onShow() {
    // 更新播放状态
    this.updatePlaybackStatus();
  },

  initData() {
    // 初始化模拟数据
    this.setData({
      hotSongs: mockData.hotSongs,
      playlists: mockData.playlists,
      playList: mockData.hotSongs
    });

    // 设置默认播放歌曲并自动播放
    if (mockData.hotSongs.length > 0) {
      const defaultSong = mockData.hotSongs[0];
      this.setData({
        currentSong: defaultSong
      });
      
      // 初始化播放列表和播放器
      app.setPlayList(mockData.hotSongs, 0);
      app.playSong(defaultSong);
    }
  },

  setupAudioListener() {
    // 监听背景音频管理器事件
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    
    backgroundAudioManager.onTimeUpdate(() => {
      this.setData({
        currentTime: Math.floor(backgroundAudioManager.currentTime)
      });
    });

    backgroundAudioManager.onPlay(() => {
      this.setData({ isPlaying: true });
    });

    backgroundAudioManager.onPause(() => {
      this.setData({ isPlaying: false });
    });

    backgroundAudioManager.onStop(() => {
      this.setData({ isPlaying: false });
    });

    backgroundAudioManager.onEnded(() => {
      this.playNext();
    });
  },

  updatePlaybackStatus() {
    const { currentSong, isPlaying } = app.globalData;
    if (currentSong) {
      this.setData({
        currentSong: { ...currentSong, isPlaying },
        isPlaying
      });
    }
  },

  // 搜索功能
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  onSearchConfirm() {
    this.performSearch();
  },

  onSearch() {
    this.setData({
      showSearchModal: true
    });
  },

  closeSearchModal() {
    this.setData({
      showSearchModal: false,
      searchKeyword: '',
      searchResults: []
    });
  },

  performSearch() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      this.setData({ searchResults: [] });
      return;
    }

    const results = searchSongs(keyword);
    this.setData({ searchResults: results });
  },

  // 播放控制
  playSong(e) {
    const index = e.currentTarget.dataset.index;
    const song = this.data.hotSongs[index];
    
    if (song) {
      this.setData({
        currentSong: song,
        currentIndex: index
      });
      
      app.playSong(song);
      app.setPlayList(this.data.hotSongs, index);
    }
  },

  playSearchResult(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      this.setData({
        currentSong: song,
        showSearchModal: false,
        searchKeyword: ''
      });
      
      app.playSong(song);
      // 将搜索到的歌曲添加到播放列表
      const newPlayList = [...this.data.playList, song];
      app.setPlayList(newPlayList, newPlayList.length - 1);
    }
  },

  togglePlay() {
    // 如果没有当前歌曲，使用默认歌曲
    if (!this.data.currentSong && this.data.hotSongs.length > 0) {
      const defaultSong = this.data.hotSongs[0];
      this.setData({
        currentSong: defaultSong
      });
      app.setPlayList(this.data.hotSongs, 0);
      app.playSong(defaultSong);
    } else {
      app.togglePlay();
      // 使用updatePlaybackStatus来同步状态，而不是直接设置
      this.updatePlaybackStatus();
    }
  },

  playNext() {
    // 如果没有当前歌曲，使用默认歌曲
    if (!this.data.currentSong && this.data.hotSongs.length > 0) {
      const defaultSong = this.data.hotSongs[0];
      this.setData({
        currentSong: defaultSong
      });
      app.setPlayList(this.data.hotSongs, 0);
      app.playSong(defaultSong);
    } else {
      app.playNext();
      this.updatePlaybackStatus();
    }
  },

  playPrev() {
    // 如果没有当前歌曲，使用默认歌曲
    if (!this.data.currentSong && this.data.hotSongs.length > 0) {
      const defaultSong = this.data.hotSongs[0];
      this.setData({
        currentSong: defaultSong
      });
      app.setPlayList(this.data.hotSongs, 0);
      app.playSong(defaultSong);
    } else {
      app.playPrev();
      this.updatePlaybackStatus();
    }
  },

  onProgressChange(e) {
    const time = e.detail.value;
    this.setData({ currentTime: time });
    
    // 实际项目中这里应该设置音频播放位置
    // app.backgroundAudioManager.seek(time);
  },

  // 收藏功能
  toggleFavorite() {
    const currentSong = this.data.currentSong;
    if (currentSong) {
      this.setData({
        currentSong: {
          ...currentSong,
          isFavorite: !currentSong.isFavorite
        }
      });
      
      // 实际项目中这里应该保存到收藏列表
      wx.showToast({
        title: currentSong.isFavorite ? '取消收藏' : '收藏成功',
        icon: 'success'
      });
    }
  },

  // 歌单功能
  viewPlaylist(e) {
    const playlistId = e.currentTarget.dataset.id;
    wx.showToast({
      title: `打开歌单 ${playlistId}`,
      icon: 'none'
    });
  },

  viewAllPlaylists() {
    wx.showToast({
      title: '查看所有歌单',
      icon: 'none'
    });
  },

  onSettings() {
    wx.showToast({
      title: '打开设置',
      icon: 'none'
    });
  },

  // 播放模式切换
  switchPlayMode() {
    const newMode = app.switchPlayMode();
    const modeIcons = {
      'sequence': 'icon-sequence',
      'random': 'icon-random',
      'loop': 'icon-loop'
    };
    
    this.setData({
      playMode: newMode,
      playModeIcon: modeIcons[newMode]
    });
  },

  // 歌词显示切换
  toggleLyric() {
    const showLyric = !this.data.showLyric;
    this.setData({ showLyric });
    
    if (showLyric && this.data.currentSong) {
      this.loadLyricData(this.data.currentSong);
    }
  },

  // 加载歌词数据
  loadLyricData(song) {
    if (!song) return;
    
    const lyricData = app.loadLyricData(song);
    this.setData({ lyricData });
  },

  // 播放歌曲时加载歌词
  playSong(e) {
    const index = e.currentTarget.dataset.index;
    const song = this.data.hotSongs[index];
    
    if (song) {
      this.setData({
        currentSong: song,
        currentIndex: index
      });
      
      app.playSong(song);
      app.setPlayList(this.data.hotSongs, index);
      
      // 加载歌词数据
      if (this.data.showLyric) {
        this.loadLyricData(song);
      }
    }
  },

  // 搜索播放时加载歌词
  playSearchResult(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      this.setData({
        currentSong: song,
        showSearchModal: false,
        searchKeyword: ''
      });
      
      app.playSong(song);
      // 将搜索到的歌曲添加到播放列表
      const newPlayList = [...this.data.playList, song];
      app.setPlayList(newPlayList, newPlayList.length - 1);
      
      // 加载歌词数据
      if (this.data.showLyric) {
        this.loadLyricData(song);
      }
    }
  },

  // 更新播放状态时同步歌词
  updatePlaybackStatus() {
    const { currentSong, isPlaying, currentTime } = app.globalData;
    if (currentSong) {
      this.setData({
        currentSong: { ...currentSong, isPlaying },
        isPlaying,
        currentTime: currentTime || 0
      });
    }
  },

  // 分享功能
  shareSong() {
    const { currentSong } = this.data;
    if (!currentSong) {
      wx.showToast({
        title: '请先选择歌曲',
        icon: 'none'
      });
      return;
    }

    const shareInfo = app.shareSong(currentSong);
    
    wx.showShareMenu({
      withShareTicket: true
    });

    wx.showToast({
      title: '分享内容已生成',
      icon: 'success'
    });
  },

  // 页面分享配置
  onShareAppMessage() {
    const { currentSong } = this.data;
    if (currentSong) {
      return app.shareSong(currentSong);
    }
    
    return {
      title: '音乐播放器 - 发现好音乐',
      path: '/pages/index/index',
      imageUrl: '/images/share-default.jpg'
    };
  },

  // 工具函数
  formatTime(seconds) {
    if (!seconds) return '0:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }
});